import { handleActions as createReducer } from "redux-actions";
import { addProductToLocalCart, changeLocalProductNumber, deleteProductFromLocalCart, saveCarts } from "../actions/cart.actions";

const initialState = []

// 将商品添加到本地购物车数据中
const handleAddProductToLocalCart = (state,action) => {
  // 1.要添加的商品没有在购物车中 直接添加
  // 2.要添加的商品已在购物车中 商品数量加一
  const newState = JSON.parse(JSON.stringify(state))
  
  const product = newState.find(product=> product.id === action.payload.id)
  if(product){
    product.count = product.count + 1
  }else{
    newState.push(action.payload)
  }
  return newState
}

// 将服务器返回的数据同步到本地
const handleSaveCarts = (state,action) => action.payload

// 删除购物车的商品
const handleDeleteProductFromLocalCart = (state,action) => {
  const newState = JSON.parse(JSON.stringify(state))
  newState.splice(action.payload,1)
  return newState
}

// 更改购物车商品数量
const handleChangeLocalProductNumber = (state,action) => {
  const newState = JSON.parse(JSON.stringify(state))
  const product = newState.find(product=> product.id === action.payload.id)
  product.count = action.payload.count
  return newState
}

export default createReducer({
  // 将商品添加到本地购物车数据中
  [addProductToLocalCart]: handleAddProductToLocalCart,
  // 将服务器返回的数据同步到本地
  [saveCarts]: handleSaveCarts,
  // 删除购物车的商品
  [deleteProductFromLocalCart]: handleDeleteProductFromLocalCart,
  // 更改购物车商品数量
  [changeLocalProductNumber]: handleChangeLocalProductNumber
},initialState)